<?php

namespace app\controller;

use app\model\Device;
use app\model\DeviceUser;
use support\Request;
use Workerman\Mqtt\Client;

class DeviceController extends BaseController
{


    public function index(Request $request)
    {

        // Log::info('index', $request->user);

        $deviceId = $request->get('id');

        $user = $this->getUser($request);

        $devices = $user->devices;

        if($deviceId){
            $devices = $devices->where('id', $deviceId);
        }

        foreach($devices  as $key =>$device){

            // dump($device->deviceName->name);

            $device['name'] = $device->deviceName->name;
            // $device[$key] = $device;
        }

        return $this->success(
            [
                'code' => 200,
                'msg' => '成功',
                'data' => array_values($devices->sortKeysDesc()->toArray()),
            ]
        );
    }
    public function bindUser(Request $request)
    {

        try {
            $deviceSn = $request->post('sn');

            $device = Device::query()->where('sn', $deviceSn)->firstOrFail();

            $userId = $this->getUserId($request);

            if ($device->id && $userId) {
                $device = DeviceUser::firstOrCreate([
                    'user_id' => $userId,
                    'device_id' => $device->id,
                ]);
                return $this->success($device);
            } else {
                return $this->error('失败');
            }
        } catch (\Throwable $th) {
            return $this->error($th->getMessage());
        }
    }

    public function unbindUser(Request $request)
    {
        $deviceId = $request->post('device_id');
        $userId = $this->getUserId($request);
        $deviceUser = DeviceUser::where([
            'user_id' => $userId,
            'device_id' => $deviceId,
        ])->first();

        if (!empty($deviceUser)) {
            DeviceUser::query()->where('id', $deviceUser->id)->delete();
            return $this->success('成功');
        } else {
            return $this->error('解绑失败');
        }
    }

    public function switchPower(Request $request)
    {
        try {
            $deviceId = $request->post('device_id');

            $device = Device::query()->findOrFail($deviceId);

            if (!is_null($status = $request->post('status', null))) {
                $device->status = $status;
                $device->save();

                //发布指令
                $this->publish('Topic_RETURN', json_encode(['GATEID' => $device->gateway_id, 'CONTROL' => $status ]));

            }

            return $this->success('成功');
        } catch (\Throwable $th) {
            return $this->error($th->getMessage());
        }
    }

    public function publish($topic,$msg)
    {
        $mqtt = new Client(config('mqtt.server').':'.config('mqtt.port'), config('mqtt.options'));
        $mqtt->onConnect = function($mqtt) use ($topic, $msg){
            $mqtt->publish($topic, $msg);
        };
        $mqtt->connect();
    }
}
